package app.fugema.shop.main.login.view;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.base.common.app.LoginUtils;
import com.base.common.model.http.err.ApiException;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.Base64Utils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.VerifyUtils;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewObserver;

import app.fugema.shop.R;
import app.fugema.shop.databinding.SafetyVerificationFragmentBinding;
import app.fugema.shop.main.login.model.CheckImgResult;
import app.fugema.shop.main.login.model.CheckVerCodeResult;
import app.fugema.shop.main.login.vm.LoginVM;
import app.fugema.shop.main.setting.model.ContactResult;
import app.fugema.shop.util.SimpleTextWatcher;

/**
 * 安全验证
 */
public class SafetyVerificationFragment extends BaseFragment<SafetyVerificationFragmentBinding, LoginVM> {

    public static SafetyVerificationFragment newInstance()
    {
        Bundle args = new Bundle();
        SafetyVerificationFragment fragment = new SafetyVerificationFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //图片验证码
    private CheckImgResult imgCodeResult;

    private String mobile;

    private CheckVerCodeResult verCodeResult;

    @Override
    protected SafetyVerificationFragmentBinding initDataBinding(LayoutInflater inflater, ViewGroup container) {
        return DataBindingUtil.inflate(inflater, R.layout.safety_verification_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        //验证发送验证码
        binding.btnSendCode.setOnClickListener(new OnClickCheckedUtil()
        {
            @Override
            public void onClicked(View view)
            {
                String phoneVerfCode = binding.etPhoneCode.getText().toString();
                if (!phoneVerfCode.isEmpty())
                {
                    checkPhoneVerfyCode( phoneVerfCode );
                }
                else
                {
                    UIUtils.showToastSafes("验证码不能为空");
                }
            }
        });
        //下一步
        binding.btnSubmit.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                nextStep();
            }
        });
        binding.etPhoneCode.addTextChangedListener(new SimpleTextWatcher()
        {
            @Override
            public void afterTextChanged(String content)
            {
                if( UIUtils.isNotEmpty( content ) )
                {
                    binding.btnSendCode.setEnabled(true);
                    binding.btnSendCode.setAlpha(1f);
                }
                else
                {
                    binding.btnSendCode.setEnabled(false);
                    binding.btnSendCode.setAlpha(0.6f);
                }
            }
        });

        binding.etPhoneNO.addTextChangedListener(new SimpleTextWatcher() {

            @Override
            public void afterTextChanged(String content)
            {
                if (UIUtils.isNotEmpty(content))
                {
                    binding.btnSubmit.setEnabled(true);
                    binding.btnSubmit.setAlpha(1f);
                }
                else
                {
                    binding.btnSubmit.setEnabled(false);
                    binding.btnSubmit.setAlpha(0.6f);
                }
            }
        });
        VerifyUtils.onTextChangedPhone(binding.etPhoneNO);
        String s = binding.etPhoneNO.getText().toString().trim();
        if (s.length() == 0)
        {
            binding.btnSubmit.setEnabled(false);
            binding.btnSubmit.setAlpha(0.6f);
        }

        binding.llImgCodeView.setVisibility(View.VISIBLE);
        binding.llVerfyCodeView.setVisibility(View.GONE);

    }

    @Override
    public void initData()
    {
        super.initData();
        //先获取图片 验证码
        getImgVerfyCode();
    }

    @Override
    public void onUserVisible()
    {
        super.onUserVisible();
        LogUtil.e("SafetyVerificationFragment","LazyLoad 第一次可见");

    }

    private void queryBindPhone()
    {
        if(LoginUtils.isLogin())
        {
            String userKey = LoginUtils.getToken();
            viewModel.getUserBindPhone(userKey)
                     .observe(this, new BaseViewObserver<LiveDataWrapper<ContactResult>>()
                     {
                         @Override
                         protected void onSuccess(LiveDataWrapper<ContactResult> data)
                         {
                             if( data.data.isSuccess() && UIUtils.isNotEmpty( data.data.getContact() ) )
                             {
                                      binding.etPhoneNO.setText( data.data.getContact() );
                             }
                             else
                             {
                                     UIUtils.showToastSafes( "请先绑定手机号",R.mipmap.ic_toast_warn );
                                     ((ForgetPassWordActivity) mActivity).finish();
                             }
                         }
                     });
        }
    }

    /***
     * 下一步，校验图片验证码 并向手机发送验证码
     */
    private void nextStep()
    {
        mobile = binding.etPhoneNO.getText().toString().replaceAll(" ", "");
        String msgCode = binding.etMsgCode.getText().toString();

        if (mobile.isEmpty())
        {
            UIUtils.showToastSafes("手机号不能为空");
            return;
        }

        if (msgCode.isEmpty()) {
            UIUtils.showToastSafes("验证码不能为空");
            return;
        }
        //验证图片验证码并发送手机验证码
        viewModel.sendVerifyCode(imgCodeResult.getId(), mobile, msgCode)
                .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity())
                {
                    @Override
                    protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                    {
                        if( data.data.isSuccess() )
                        {
                            UIUtils.showToastSafes( data.data.getMsg() );
                            showSendMobileCode();
                        }
                    }

                    @Override
                    protected void onError(ApiException error)
                    {
                        super.onError(error);
                        UIUtils.showToastSafes(error.getMessage());
                    }
                });
    }


    /**
     * 获取图形验证码
     */
    private void getImgVerfyCode()
    {
        viewModel.getImgCheckCode()
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CheckImgResult>>(getActivity()) {
                    @Override
                    protected void onSuccess(LiveDataWrapper<CheckImgResult> data)
                    {
                        if( UIUtils.isNotEmpty( data.data.getFileContents() ) )
                        {
                            imgCodeResult = data.data;
                            //LogUtil.e( data.data.getFileContents() );
                            // 显示 图片验证码
                            binding.ivVerCode.setImageBitmap( Base64Utils.base64ToBitmap(data.data.getFileContents()) );
                        }
                        //starTimeCountDown();
                        //UIUtils.showToastSafes(data.getMsg());

                        //延迟 查找绑定的手机
                        if( ((ForgetPassWordActivity) mActivity).isFindPayPwd() )
                        {
                            queryBindPhone();
                        }
                    }

                    @Override
                    protected void onError(ApiException error)
                    {
                        UIUtils.showToastSafes(error.getMessage());
                    }
                });
    }

    /**
     * 验证手机验证码 拿到修改密码的 cert
     */
    private void checkPhoneVerfyCode( String  phoneVerfCode)
    {
        viewModel.checkPhoneVerifyCode(mobile,phoneVerfCode)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CheckVerCodeResult>>() {
                     @Override
                     protected void onSuccess(LiveDataWrapper<CheckVerCodeResult> data)
                     {
                         if( data.data.isSuccess() )
                         {
                             verCodeResult = data.data;
                             //滑动到设置密码
                             if (getActivity() instanceof ForgetPassWordActivity)
                             {
                                 ForgetPassWordActivity forgetPassWordActivity = (ForgetPassWordActivity) getActivity();
                                 forgetPassWordActivity.setCert(verCodeResult.getCertificate());
                                 forgetPassWordActivity.setNewPasswordView();
                             }
                         }
                     }
                 });
    }

    private void showSendMobileCode()
    {
        binding.llImgCodeView.setVisibility(View.GONE);
        binding.llVerfyCodeView.setVisibility(View.VISIBLE);

        binding.tvPhoneCodeTips.setText( "验证码已发送至"+mobile );
    }

    private final int mTotalCountDown = 60 * 1000;
    private CountDownTimer mCountDownTimer;

    /**
     * 开始倒计时
     */
    private void starTimeCountDown()
    {
        /*
        binding.btnSendCode.setEnabled(false);
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(mTotalCountDown, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    binding.btnSendCode.setText((millisUntilFinished / 1000) + "s");
                }

                @Override
                public void onFinish() {
                    binding.btnSendCode.setEnabled(true);
                    binding.btnSendCode.setText("获取验证码");
                }
            };
        }
        */
        mCountDownTimer.start();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }
}
